package com.android.qjpmc.application_module.station.fragment;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.android.qjpmc.R;
import com.android.qjpmc.application_module.home.viewModel.HomeViewModel;
import com.android.qjpmc.databinding.FragmentStationPwrDiagramBinding;
import com.android.qjpmc.kernel.PwrDiagramObject;
import com.android.qjpmc.kernel.StateCompt;
import com.android.qjpmc.view.JxtView;
import com.android.qjpmc.widget.mvvm.factory.CreateViewModel;
import com.android.qjpmc.widget.mvvm.view.BaseMVVMFragment;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

@CreateViewModel(HomeViewModel.class)
public class PwrDiagramFragment extends BaseMVVMFragment<HomeViewModel, FragmentStationPwrDiagramBinding>{
    @Override
    public int getLayoutId() {

        return R.layout.fragment_station_pwr_diagram;
    }

    @Override
    public void initView() {
        m_JxtView = mBinding.jxtView;
        if (m_JxtView != null)
        {
            m_JxtView.m_JxtPos = 1;
        }
        else
        {
            View view = getView();
            if (view != null) {
                m_JxtView = view.findViewById(R.id.jxt_view);
            }
        }
        InitDataBuff();
        ConnectNet();
    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {

    }
    PwrDiagramObject m_JxtCnfg=null;
    public JxtView m_JxtView = null;
    int m_JxtPos=0;

    byte m_State[][];
    float m_Value[][];

    int m_Width=2160;

    byte[] buffer = new byte[256];
    int SendLen;
    byte[] buffer_r = new byte[256];
    int ReadLen;

    int InitSign=0;
    int RandCode[]=new int[2];
    int FrameID;

    MyHandler myHandler;

    int m_Port1;
    int m_Port2;

    int m_ExitSign=0;

    int m_OprType=0;
    int m_OprTypeEx=0;
    int m_StationIndex=0;
    String m_strInputPWD=null;
    String m_strOprPWD="stdq2016";
    int m_OprTime=0;
    float m_fSetValue;
    String m_strOprName=null;
/*
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.jxt, container, false);

        Active = (DataShowActivity) getActivity();
        if(Active.m_JxtSign==0) m_JxtCnfg =Active.m_Jxt.m_XmlCnfg;
        m_JxtView=new JxtView(getActivity().getApplicationContext());

        myHandler = new MyHandler();

        m_JxtView=new JxtView(getActivity().getApplicationContext());
        InitDataBuff();
        ConnectNet();


        return m_JxtView;
    }
    */

    public void InitDataBuff() {
        if(m_JxtCnfg==null) return;
        m_State=new byte[m_JxtCnfg.m_PageNum][];
        m_Value=new float[m_JxtCnfg.m_PageNum][];

        for(int i=0;i<m_JxtCnfg.m_PageNum;i++) {
            PwrDiagramObject.Page JxtPage = m_JxtCnfg.m_Page.get(i);
            if(JxtPage==null) continue;
            if(JxtPage.m_StateComptNum>0) {
                m_State[i]=new byte[JxtPage.m_StateComptNum];
                for(int j=0;j<JxtPage.m_StateComptNum;j++) {
                    m_State[i][j]=2;
                }
            }

            if(JxtPage.m_ValueComptNum>0) {
                m_Value[i]=new float[JxtPage.m_ValueComptNum];
                for(int j=0;j<JxtPage.m_ValueComptNum;j++) {
                    m_Value[i][j]=0;
                }
            }
        }
    }

    public void ConnectNet() {
        MyThread1 mt1= new MyThread1("11");
/*
        m_Port1=Active.Port1;
        m_Port2=Active.Port2;
*/
        m_ExitSign=0;

        if(m_Port1==0 && m_Port2==0) return;

        InitSign=0;
        RandCode[0]=0;
        RandCode[1]=0;
        FrameID=0x00;

        Thread t2 = new Thread(mt1);
        t2.start();

    }

    class MyThread1 implements Runnable {
        String name;
        Socket socket;

        OutputStream outputStream = null;
        InputStream inputStream = null;


        public MyThread1(String name) {
            this.name = name;
        }

        public void MakeInitFrame() {
            int Count=0;
            FrameID++;
            buffer[Count++]='@';
            buffer[Count++]=(byte)(FrameID/256);
            buffer[Count++]=(byte)(FrameID%256);
            buffer[Count++]=0x00;
            buffer[Count++]=0x00;
            buffer[Count++]=0x00;
            buffer[Count++]=0x00;
            buffer[Count++]='$';

            SendLen=Count;
        }

        public void MakeReadYCFrame() {
            int Count=0;
            FrameID++;
            buffer[Count++]='@';
            buffer[Count++]=(byte)(FrameID/256);
            buffer[Count++]=(byte)(FrameID%256);
            buffer[Count++]=0x00;
            buffer[Count++]=0x00;
            buffer[Count++]=0x22;
            buffer[Count++]=0;
            buffer[Count++]=(byte)m_JxtPos;


            if(m_JxtCnfg==null) return;
            PwrDiagramObject.Page JxtPage = m_JxtCnfg.m_Page.get(m_JxtPos);
            if(JxtPage!=null) {
                int DataNum= JxtPage.m_ValueComptNum>JxtPage.m_ValueCompt.size()?JxtPage.m_ValueCompt.size():JxtPage.m_ValueComptNum;
                buffer[Count-2] = (byte) (DataNum * 3+1);
                for (int i = 0; i < JxtPage.m_ValueComptNum && i < JxtPage.m_ValueCompt.size(); i++) {
                    PwrDiagramObject.ValueCompt ValueComptTemp = JxtPage.m_ValueCompt.get(i);
                    if (ValueComptTemp != null) {
                        buffer[Count++] = (byte) ValueComptTemp.m_StationID;
                        buffer[Count++] = (byte) ValueComptTemp.m_GroupIdx;
                        buffer[Count++] = (byte) ValueComptTemp.m_DataIdx;
                    } else {
                        buffer[Count++] = 0;
                        buffer[Count++] = 0;
                        buffer[Count++] = 0;
                    }
                }
            }

            buffer[Count++]='$';

            buffer[3]	 = (byte)(RandCode[1] & buffer[2]);
            buffer[4]	 = (byte)(RandCode[0] | buffer[5]);

            SendLen=Count;
        }

        public void MakeReadYXFrame() {
            int Count=0;
            FrameID++;
            buffer[Count++]='@';
            buffer[Count++]=(byte)(FrameID/256);
            buffer[Count++]=(byte)(FrameID%256);
            buffer[Count++]=0x00;
            buffer[Count++]=0x00;
            buffer[Count++]=0x41;
            buffer[Count++]=0;
            buffer[Count++]=(byte)m_JxtPos;

            if(m_JxtCnfg==null) return;
            PwrDiagramObject.Page JxtPage = m_JxtCnfg.m_Page.get(m_JxtPos);
            if(JxtPage!=null) {
                int DataNum= JxtPage.m_StateComptNum>JxtPage.m_StateComptList.size()?JxtPage.m_StateComptList.size():JxtPage.m_StateComptNum;
                buffer[Count-2] = (byte) (DataNum * 3+1);
                for (int i = 0; i < JxtPage.m_StateComptNum && i < JxtPage.m_StateComptList.size(); i++) {
                    StateCompt StateComptTemp = JxtPage.m_StateComptList.get(i);
                    if (StateComptTemp != null) {
                        buffer[Count++] = (byte) StateComptTemp.m_StationID;
                        buffer[Count++] = (byte) StateComptTemp.m_GroupIdx;
                        buffer[Count++] = (byte) StateComptTemp.m_DataIdx;
                    } else {
                        buffer[Count++] = 0;
                        buffer[Count++] = 0;
                        buffer[Count++] = 0;
                    }
                }
            }

            buffer[Count++]='$';

            buffer[3]	 = (byte)(RandCode[1] & buffer[2]);
            buffer[4]	 = (byte)(RandCode[0] | buffer[5]);

            SendLen=Count;
        }

        public void MakeYKFrame() {
            int Count=0;
            FrameID++;
            buffer[Count++]='@';
            buffer[Count++]=(byte)(FrameID/256);
            buffer[Count++]=(byte)(FrameID%256);
            buffer[Count++]=0x00;
            buffer[Count++]=0x00;
            buffer[Count++]=0x11;
            buffer[Count++]=0x0A;
            buffer[Count++]=(byte)m_OprTypeEx;
            buffer[Count++]=(byte)(m_StationIndex);
            buffer[Count++]=(byte)0xCC;
            buffer[Count++]=0x00;

            buffer[Count++]=0x00;
            buffer[Count++]=0x00;
            buffer[Count++]=0x00;
            buffer[Count++]=0x00;
            buffer[Count++]=0x00;
            buffer[Count++]=0x00;

            buffer[Count++]='$';

            buffer[3]	 = (byte)(RandCode[1] & buffer[2]);
            buffer[4]	 = (byte)(RandCode[0] | buffer[5]);

            m_OprType=0;

            SendLen=Count;
        }

        public void MakeYTFrame() {
            int Count=0;
            FrameID++;
            buffer[Count++]='@';
            buffer[Count++]=(byte)(FrameID/256);
            buffer[Count++]=(byte)(FrameID%256);
            buffer[Count++]=0x00;
            buffer[Count++]=0x00;
            buffer[Count++]=0x12;
            buffer[Count++]=0x0D;
            buffer[Count++]=0x02;
            buffer[Count++]=(byte)(m_StationIndex);

            long Value = Float.floatToIntBits(m_fSetValue);
            buffer[Count++]=(byte)(Value&0xff);
            buffer[Count++]=(byte)((Value>>8)&0xff);
            buffer[Count++]=(byte)((Value>>16)&0xff);
            buffer[Count++]=(byte)((Value>>24)&0xff);

            buffer[Count++]=0x00;

            buffer[Count++]=0x00;
            buffer[Count++]=0x00;
            buffer[Count++]=0x00;
            buffer[Count++]=0x00;
            buffer[Count++]=0x00;
            buffer[Count++]=0x00;

            buffer[Count++]='$';

            buffer[3]	 = (byte)(RandCode[1] & buffer[2]);
            buffer[4]	 = (byte)(RandCode[0] | buffer[5]);

            m_OprType=0;

            SendLen=Count;
        }

        public void run() {
            try {// 创建一个Socket对象，并指定服务端的IP及端口号

                FrameID=0x00;
                int ErrorCount=0;
                int Count=0;

                for(;;) {

                    if(m_ExitSign==1) {
                        if(socket!=null) {
                            if(socket.isConnected()) {
                                outputStream.close();
                                inputStream.close();
                                socket.close();
                            }
                        }
                        break;
                    }

                    if(socket==null || !socket.isConnected())
                        socket = new Socket("39.108.172.55", m_Port1);
                    if(!socket.isConnected())
                    {
                        Message msg = myHandler.obtainMessage();
                        Bundle b = new Bundle();
                        b.putString("info", "connect fail_1!");
                        msg.setData(b);
                        //传递数据
                        myHandler.sendMessage(msg); // 向Handler发送消息,更新UI

                        socket.close();

                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        continue;
                    }

                    Message msg_S = myHandler.obtainMessage();
                    Bundle b_S = new Bundle();
                    b_S.putString("info", "connect success!");
                    msg_S.setData(b_S);
                    //传递数据
                    myHandler.sendMessage(msg_S); // 向Handler发送消息,更新UI

                    outputStream = socket.getOutputStream();
                    inputStream = socket.getInputStream();

                    Count++;

                    if(m_OprTime>0) m_OprTime++;
                    if(m_OprTime>=20) {
                        Message msg = myHandler.obtainMessage();
                        Bundle b = new Bundle();
                        b.putString("info", "Opr_Fail!");
                        msg.setData(b);
                        //传递数据
                        myHandler.sendMessage(msg); // 向Handler发送消息,更新UI
                        m_OprTime=0;

                    }

                    if(InitSign==0) {
                        MakeInitFrame();
                    }
                    else {
                        if(m_OprType==1) MakeYKFrame();
                        else if(m_OprType==2) MakeYTFrame();
                        else if(Count%5==1) MakeReadYCFrame();
                        else if(Count%5==2) MakeReadYXFrame();
                        else {
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            continue;
                        }
                    }

                    if(Count>=100) Count=0;

                    outputStream.write(buffer, 0, SendLen);
                    outputStream.flush();

                    for(int j=0;j<10;j++) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }



                        if(m_ExitSign==1) break;
                        if(inputStream.available()>0) {
                            ReadLen = inputStream.read(buffer_r, 0, inputStream.available());

                            if (ReadLen > 0 && ReadLen<256) {
                                ErrorCount = 0;
                                Message msg_1 = myHandler.obtainMessage();
                                Bundle b1 = new Bundle();

                                b1.putString("info", "Recv_Data_Success");
                                msg_1.setData(b1);
                                //传递数据
                                myHandler.sendMessage(msg_1); // 向Handler发送消息,更新UI
                                break;
                            }
                        }
                        else {
                            ErrorCount++;
                            if(ErrorCount>100) {
                                outputStream.close();
                                inputStream.close();
                                socket.close();
                                ErrorCount=0;
                                break;
                            }
                        }
                    }

                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    int WaitCount=0;
                    while(ReadLen>0 && WaitCount<4) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        WaitCount++;
                    }
                }


                Message msg_F = myHandler.obtainMessage();
                Bundle b_F = new Bundle();
                b_F.putString("info", "Close Net!");
                msg_F.setData(b_F);
                //传递数据
                myHandler.sendMessage(msg_F); // 向Handler发送消息,更新UI


                outputStream.close();
                inputStream.close();
                socket.close();
            } catch (UnknownHostException e) {
                Message msg = myHandler.obtainMessage();
                Bundle b = new Bundle();
                b.putString("info","connect fail_2!");
                msg.setData(b);
                //传递数据
                myHandler.sendMessage(msg); // 向Handler发送消息,更新UI

                e.printStackTrace();

            } catch (IOException e) {
                Message msg = myHandler.obtainMessage();
                Bundle b = new Bundle();
                b.putString("info","connect fail_3!");
                msg.setData(b);
                //传递数据
                myHandler.sendMessage(msg); // 向Handler发送消息,更新UI
                e.printStackTrace();

            }
        }
    }



    class MyHandler extends Handler {
        public MyHandler() {
            //R.color.common_signin_btn_text_light
        }


        public  float getFloat(byte[] b, int index) {
            int l;
            l = b[index + 0];
            l &= 0xff;
            l |= ((long) b[index + 1] << 8);
            l &= 0xffff;
            l |= ((long) b[index + 2] << 16);
            l &= 0xffffff;
            l |= ((long) b[index + 3] << 24);
            return Float.intBitsToFloat(l);
        }

        public void handleMessage(Message msg) {
            // 这里用于更新UI
            Bundle b = msg.getData();
            String Result = b.getString("info");

            String Success="Recv_Data_Success";
            String Fail="Opr_Fail!";
            if( Result.equals(Success) ) {
                if (ReadLen < 7) {ReadLen=0;return;}
                if (buffer_r[0] != '@' || buffer_r[ReadLen - 1] != '$') {ReadLen=0;return;}
                int iFrameId_low= buffer_r[2]&0xff;
                int iFrameId_Hign= buffer_r[1]&0xff;
                if (iFrameId_Hign != FrameID / 256 || iFrameId_low != FrameID % 256) {ReadLen=0;return;}

                RandCode[0] = buffer_r[3];
                RandCode[1] = buffer_r[4];

                int FuncCode=buffer_r[5]&0xff;

                if (FuncCode == 0x80) InitSign = 1;
                else if (FuncCode==0xA2){
                    if(buffer_r[7]!=m_JxtPos) {ReadLen=0;return;}
                    for (int i = 0; i < buffer_r[8]; i++) {
                        float fValue=getFloat(buffer_r,i * 4 + 9);
                        m_Value[m_JxtPos][i]= fValue;
                    }
                }
                else if(FuncCode==0xA1)
                {
                    if(buffer_r[7]!=m_JxtPos) {ReadLen=0;return;}
                    int YXbitNum=buffer_r[8]&0xff;
                    int YXByteSum=((YXbitNum-1)/8+1);
                    for(int i=0;i<YXByteSum;i++) {
                        int k;
                        byte byYxStatus = 0x01;
                        for (k = 0; k < 8; k++) {
                            if(i*8+k >= YXbitNum) break;
                            int bTemp;
                            bTemp = (int) (byYxStatus << k);
                            if((buffer_r[9 + i] & bTemp) > 0) m_State[m_JxtPos][i*8+k]=1;
                            else m_State[m_JxtPos][i*8+k]=0;
                        }
                    }
                }
                else if(FuncCode==0xC1)
                {
                    if(buffer_r[7]!=m_JxtPos) {ReadLen=0;return;}
                    int YXByteSum=buffer_r[8];
                    for(int i=0;i<YXByteSum;i++) {
                        m_State[m_JxtPos][i]=buffer_r[9+i];
                    }
                }
                else if(FuncCode==0x89){
/*
                    Active.mNotificationManager.notify(Active.notifyId, Active.mBuilder.build());


 */
                }
                else if (FuncCode==0x91){
                    String strTemp="";
                    strTemp+=m_strOprName;
                    strTemp+="命令已下发！";
                    new  AlertDialog.Builder(getActivity())
                            .setTitle("信息" )
                            .setMessage(strTemp )
                            .setPositiveButton("确定" ,  null )
                            .show();
                    m_OprTime=0;
                }
                else if(FuncCode==0x92)
                {
                    String strTemp="";
                    strTemp+=m_strOprName;
                    strTemp+="命令已下发！";
                    new  AlertDialog.Builder(getActivity())
                            .setTitle("信息" )
                            .setMessage(strTemp )
                            .setPositiveButton("确定" ,  null )
                            .show();
                    m_OprTime=0;
                }
                else {ReadLen=0;return;}
            }
            else if(Result.equals(Fail) )
            {
                String strTemp="";
                strTemp+=m_strOprName;
                strTemp+="命令下发失败！";
                new  AlertDialog.Builder(getActivity())
                        .setTitle("错误" )
                        .setMessage(strTemp )
                        .setPositiveButton("确定" ,  null )
                        .show();
                m_OprTime=0;
            }

            b.clear();

            ReadLen=0;
        }
    }

}

